<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者姓名" prop="patientName">
        <el-input
            v-model="queryParams.patientName"
            placeholder="请输入患者姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNo">
        <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入订单号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="操作时间" prop="operateTime">
        <el-date-picker clearable
                        v-model="queryParams.operateTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择操作时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="来源" prop="source">
        <el-input
            v-model="queryParams.source"
            placeholder="请输入来源"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付金额" prop="amount">
        <el-input
            v-model="queryParams.amount"
            placeholder="请输入支付金额"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:records:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:records:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:records:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:records:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="就诊卡号" align="center" prop="id" />
      <el-table-column label="患者姓名" align="center" prop="patientName" />
      <el-table-column label="订单号" align="center" prop="orderNo" />
      <el-table-column label="操作时间" align="center" prop="operateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.operateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="来源" align="center" prop="source" />
      <el-table-column label="业务类型" align="center" prop="bizType" />
      <el-table-column label="费用类型" align="center" prop="feeType" />
      <el-table-column label="支付方式" align="center" prop="payType" />
      <el-table-column label="支付金额" align="center" prop="amount" />
      <el-table-column label="缴费状态" align="center" prop="payStatus" >
      <template #default="scope">
          <span :style="{ color: scope.row.payStatus === '已缴费' ? 'green' : scope.row.payStatus === '未缴费' ? 'red' : 'inherit' }">
            {{ scope.row.payStatus }}
          </span>
      </template>
        </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:records:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:records:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改门诊充值记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-divider content-position="center">患者信息</el-divider>
      <el-form ref="recordsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="患者姓名" prop="patientName">
          <el-select v-model="form.patientName" placeholder="请选择患者" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in patientsList" :key="index" :value="item.id"
                       :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件类型">
          <el-input v-model="zjlx" disabled/>
        </el-form-item>
        <el-form-item label="微信昵称">
          <el-input v-model="wxnc" disabled/>
        </el-form-item>
        <el-form-item label="就诊地址">
          <el-input v-model="jzrdz" disabled/>
        </el-form-item>
        <el-form-item label="就诊卡号" prop="id">
          <el-input v-model="zycardNo" placeholder="请输入就诊卡号" disabled/>
        </el-form-item>
        <el-form-item label="证件号码">
          <el-input v-model="zjhm" disabled/>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="sj" disabled/>
        </el-form-item>
        <div class="avatar-uploader">
          <!-- 文本内容 -->
          <span class="text">患者头像</span>

          <!-- 圆形相框 -->
          <div
              class="avatar-frame"
              @click="triggerFileInput"
          >
            <!-- 显示上传的头像或默认空白 -->
            <img
                v-if="avatarUrl"
                :src="avatarUrl"
                alt="用户头像"
                class="avatar-image"
            />
            <div v-else class="empty-frame">
            </div>

            <!-- 隐藏的文件输入 -->
            <input
                type="file"
                ref="fileInput"
                @change="handleFileChange"
                accept="image/*"
                style="display: none;"
            />
          </div>
        </div>

        <el-form-item label="关系" style="padding-top: 20px">
          <el-input v-model="gx"/>
        </el-form-item>
      </el-form>
      <el-divider content-position="center">就诊信息</el-divider>
      <el-form ref="recordsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="就诊医院">
          <el-select v-model="form.name" placeholder="请选择就诊医院" clearable>
            <el-option
                v-for="dept in hName"
                :key="dept"
                :label="dept"
                :value="dept"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="医院地址">
          <el-select v-model="form.address" placeholder="请选择医院地址" clearable>
            <el-option
                v-for="dept in hAddress"
                :key="dept"
                :label="dept"
                :value="dept"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="就诊科室">
          <el-select v-model="form.department" placeholder="请选择就诊科室" clearable>
            <el-option
                v-for="dept in departmentOptions"
                :key="dept"
                :label="dept"
                :value="dept"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="就诊医生">
          <el-select v-model="form.name" placeholder="请选择就诊医生" clearable>
            <el-option
                v-for="dept in doctorsList"
                :key="dept"
                :label="dept"
                :value="dept.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="医生职称" >
          <el-select v-model="form.title" placeholder="请选择医生职称" clearable>
            <el-option
                v-for="dept in doctorsListzc"
                :key="dept"
                :label="dept"
                :value="dept.title"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业务类型" prop="bizType">
          <el-input v-model="form.bizType" placeholder="请输入业务类型" />
        </el-form-item>
        <el-form-item label="费用类型" prop="feeType">
          <el-input v-model="form.feeType" placeholder="请输入费用类型" />
        </el-form-item>
        <el-form-item label="费用明细">
        </el-form-item>
        <div class="bottom">
          <table class="fee-table">
            <thead>
            <tr>
              <th>序号</th>
              <th>项目名称</th>
              <th>单价（元）</th>
              <th>数量</th>
              <th>小计（元）</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item, index) in feeList" :key="index">
              <td>{{ index + 1 }}</td>
              <td>{{ item.name }}</td>
              <td>{{ item.price }}</td>
              <td>{{ item.quantity }}</td>
              <td>{{ item.subtotal }}</td>
            </tr>
            </tbody>
          </table>
        </div>

        <el-divider content-position="center">订单信息</el-divider>
        <el-form ref="recordsRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="操作时间" prop="operateTime">
            <el-date-picker clearable
                            v-model="form.operateTime"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择操作时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="订单编号" prop="orderNo">
            <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
          </el-form-item>
          <el-form-item label="支付金额" prop="amount">
            <el-input v-model="form.amount" placeholder="请输入支付金额" />
          </el-form-item>
          <el-form-item label="支付方式" prop="payType">
            <el-input v-model="form.payType" placeholder="请输入支付方式" />
          </el-form-item>
          <el-form-item label="卡内余额" prop="balance">
            <el-input v-model="balance" placeholder="请输入卡内余额" />
          </el-form-item>
          <el-form-item label="订单状态" prop="payStatus">
            <el-input v-model="form.payStatus" placeholder="请输入订单状态" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="input" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Records">
import { listRecords, getRecords, delRecords, addRecords, updateRecords } from "@/api/system/records"
import {getDepartmentNames} from "@/api/system/departments"
import {listDoctors} from "@/api/system/doctors"
import {listCampus} from "@/api/system/hospitalCampus.js"
import { listPatients,getPatients } from "@/api/system/patients.js"
import {reactive, ref, watch} from "vue";

const { proxy } = getCurrentInstance()

const recordsList = ref([])
const feeRecordsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const gx = ref('本人')
const zjlx = ref('身份证号')
const wxnc = ref('')
const jzrdz = ref('')
const zjhm = ref('')
const sj = ref('')
const zycardNo = ref('')
const jzyy=ref('北京市第一人民医院/东院')
const yydz=ref('北京市大兴区**路990号')
const jzks=ref('消化内科-门诊3楼东区501')
const jzys=ref('赵马')
const yszc=ref('主任医师')
const checkedFeeRecords = ref([])
const fileInput = ref(null);
const avatarUrl = ref('');
const balance = ref(2000)
const input =   ref('')
const doctorsList = ref([])
const doctorsListzc = ref([])
const departmentOptions = ref([]);
const hName= ref([]);
const hAddress= ref([]);
const feeList = ref([
  { name: '雷梦罗布片', price: 50.00, quantity: 2, subtotal: 100.00 },
  { name: '阿司匹林肠溶片', price: 40.00, quantity: 2, subtotal: 80.00 },
  { name: '雷梦罗布片', price: 50.00, quantity: 2, subtotal: 100.00 },
  { name: '阿司匹林肠溶片', price: 40.00, quantity: 2, subtotal: 80.00 }
]);

const patientsList = ref([])
const patientid = ref('')
const campusList = ref([])
const queryParams1 = reactive({
  pageNum: 1,
  pageSize: 50,
  campusName: '' // 搜索关键词（院区名称）
})

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click();
};

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件');
      return;
    }

    // 创建文件URL并显示
    avatarUrl.value = URL.createObjectURL(file);

    // 这里可以添加实际上传逻辑
    // uploadAvatar(file);
  }
};
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    patientName: null,
    orderNo: null,
    operateTime: null,
    source: null,
    bizType: null,
    feeType: null,
    payType: null,
    amount: null,
    payStatus: null
  },
  rules: {
    patientName: [
      { required: true, message: "患者姓名不能为空", trigger: "blur" }
    ],
    orderNo: [
      { required: true, message: "订单号不能为空", trigger: "blur" }
    ],
  }
})
const { queryParams, form, rules } = toRefs(data)

watch(() => form.value.patientName, (newValue, oldValue) => {
  if (typeof newValue=="number") {
    console.log(newValue)
    getPatients(newValue).then(response => {
      console.log(response)
      wxnc.value = response.data.wechatNickname
      jzrdz.value = response.data.address
      zjhm.value = response.data.idCard
      zycardNo.value = response.data.cardNo
      sj.value = response.data.phone
      form.value.balance = response.data.cardBalance
      patientid.value = newValue
    });
  }
})

function getDoctors(){
  listDoctors(queryParams.value).then(response => {
    doctorsList.value = response.rows.map(item => item.name);
    doctorsListzc.value = response.rows.map(item => item.title);

  })
}
// function getHospitals(){
//   listCampus(queryParams.value).then(response => {
//     campusList.value = response.rows
//   })
//   console.log(ca)
// }
// getHospitals()
// 获取科室列表
function getDepartments() {
  getDepartmentNames().then(response => {
    departmentOptions.value = response.data
  })
}
getDepartments()
getDoctors()


/** 查询门诊消费记录列表 */
function getList() {
  loading.value = true
  listRecords(queryParams.value).then(async response => {
    recordsList.value = response.rows
    for (var i = 0; i < recordsList.value.length; i++) {
      recordsList.value[i].balance = (await getPatients(recordsList.value[i].patientName)).data.cardBalance
      recordsList.value[i].patientName = (await getPatients(recordsList.value[i].patientName)).data.name
    }
    total.value = response.total
    loading.value = false
  })
  listPatients().then( response => {
    patientsList.value = response.data
  })
  listCampus(queryParams1).then(response => {
    campusList.value = response.data
    console.log(response.data)
    for (var i = 0; i < campusList.value.length; i++){
      hName.value[i] = campusList.value[i].campusName
      hAddress.value[i] = campusList.value[i].address
    }
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    patientName: null,
    orderNo: null,
    operateTime: null,
    source: null,
    bizType: null,
    feeType: null,
    payType: null,
    amount: null,
    payStatus: null
  }
  feeRecordsList.value = []
  proxy.resetForm("recordsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加门诊消费记录"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getRecords(_id).then(async response => {
    let a = {}
    form.value = response.data
    a = await getPatients(form.value.patientName)
    wxnc.value = a.data.wechatNickname
    jzrdz.value = a.data.address
    zjhm.value = a.data.idCard
    sj.value = a.data.phone
    zycardNo.value = a.data.cardNo
    form.value.balance = a.data.cardBalance
    form.value.patientName = a.data.name
    patientid.value = a.data.id
    feeRecordsList.value = response.data.feeRecordsList
    open.value = true
    title.value = "修改门诊消费记录"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordsRef"].validate(valid => {
    if (valid) {
      form.value.feeRecordsList = feeRecordsList.value
      if (form.value.id != null) {
        form.value.patientName = patientid.value
        updateRecords(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRecords(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
      open.value = false
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除门诊消费记录编号为"' + _ids + '"的数据项？').then(function() {
    return delRecords(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/records/export', {
    ...queryParams.value
  }, `records_${new Date().getTime()}.xlsx`)
}

getList()
</script>
<style scoped>
.avatar-uploader {
  display: flex;
  align-items: center;
  gap: 10px;
}

.text {
  font-size: 15px;
  padding-right: 32px;
  padding-left: 10px;
  font-weight: 600;

}

.avatar-frame {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 2px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: relative;
  transition: all 0.3s ease;
  background-color: #E4EFFE;
}


.empty-frame {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  color: #ccc;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.fee-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 5px;
}
.fee-table th,
.fee-table td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: center;
}
.fee-table th {
  background-color: #E8F2FF;
  color: #666;
  font-size: 14px;
  font-weight: normal;
}

</style>